﻿using System;
using System.Collections.Generic;
using System.Linq;
using Soundteller.Audio.Model;
using Soundteller.AudioVisual.Services.Interfaces;
using Soundteller.Bus.Model.Interfaces;
using Soundteller.Visual.Model;
using Soundteller.Visual.Repositories.Interfaces;

namespace Soundteller.AudioVisual.Services
{
    public class PadStateResetter : IPadStateResetter
    {
        private readonly IGraphicRepository _graphicRepository;

        public PadStateResetter(IGraphicRepository graphicRepository)
        {
            if (graphicRepository == null) throw new ArgumentNullException("graphicRepository");

            _graphicRepository = graphicRepository;
        }

        public void Handle(IMessage message)
        {
            if (message == null) throw new ArgumentNullException("message");

            var songResetMessage = message as SongResetMessage;
            if (songResetMessage == null)
                throw new ArgumentException("Message should have type SongResetMessage", "message");

            var graphics = _graphicRepository.GetByCategory("Soundteller");
            if (!graphics.Any())
                throw new InvalidOperationException("Cannot draw pad surface, graphics not found");

            ResetPadGraphics(graphics);
        }

        private static void ResetPadGraphics(IEnumerable<GraphicBase> graphics)
        {
            foreach (var graphic in graphics)
            {
                if (graphic.Categories.Contains(GraphicCategories.PAD) && graphic.Name != "pad")
                    graphic.Name = "pad";

                if (graphic.InnerGraphics.Any())
                    ResetPadGraphics(graphic.InnerGraphics);
            }
        }

        public Type GetMessageType()
        {
            return typeof(SongResetMessage);
        }
    }
}
